package org.myy.learn.hot.二叉树.反转二叉树;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

@Slf4j
public class Solution {
    public static TreeNode invertTree(TreeNode root) {
        if(root == null){return null;}

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            TreeNode node = queue.poll();

            TreeNode lNode = node.left;
            TreeNode rNode = node.right;
            node.left = rNode;
            node.right = lNode;

            if (node.left != null){
                queue.offer(node.left);
            }
            if (node.right != null){
                queue.offer(node.right);
            }

        }
        return root;
    }

    /**
     * 构建树
     * @param values
     * @return
     */
    private static TreeNode buildTree(Integer[] values){
        if (values == null || values.length == 0){return null;}

        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int index = 1;
        while (!queue.isEmpty() && index < values.length){
            TreeNode node = queue.poll();

            //左节点
            if(index < values.length && values[index] != null){
                node.left = new TreeNode(values[index]);
                queue.offer(node.left);
            }
            index++;

            //右节点
            if(index < values.length && values[index] != null){
                node.right = new TreeNode(values[index]);
                queue.offer(node.right);
            }
            index++;

        }
        return root;
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null){return list;}

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){
            long size = queue.size();
            List<Integer> level = new ArrayList<>();
            while (size > 0){
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
            list.add(level);
        }
        return list;
    }

    public static void main(String[] args) {
        Integer[] values = new Integer[]{2,1,3};
        TreeNode root = buildTree(values);
        TreeNode invert = invertTree(root);
        List<List<Integer>> levelOrder = levelOrder(invert);
        List<Integer> flatList = levelOrder.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
        log.info("执行结束，反转二叉树={}", flatList);

    }
}
